package com.example.discover.viewmodel

import android.util.Log
import androidx.core.text.isDigitsOnly
import androidx.lifecycle.*
import com.example.discover.model.Book
import com.example.discover.repository.BookRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class BookViewModel @Inject constructor(val repository: BookRepository): ViewModel() {

    init {
        Log.i("BookViewModel","***BookViewModel instance is created***")
    }

    val books: LiveData<List<Book>> by lazy {
        repository.getAll().asLiveData()
    }

    val book : LiveData<Book> by lazy {
        Transformations.map(books){ it -> if (it.isEmpty()) { Book("","","") } else { it.lastOrNull()} }
    }

    val totalPrice: LiveData<String> by lazy {
        Transformations.switchMap(books) { it -> calTotalPrice(it) }
    }

    val totalSize: LiveData<String> by lazy {
        Transformations.switchMap(books){ it -> MutableLiveData<String> (it.size.toString())}
    }

    companion object {
        fun calTotalPrice(books: List<Book>): LiveData<String> {
            var sum = 0
            books.forEach {
                if (it.price.isDigitsOnly()) {
                    sum += it.price.toInt()
                }
            }
            return MutableLiveData<String> (sum.toString())
        }
    }

    //Launching a new coroutine to insert the data in a non-blocking way
    fun add(book: Book) =  viewModelScope.launch{
        repository.insert(*arrayOf(book))
    }

    fun remove(isbn: String) =  viewModelScope.launch{
        repository.delete(isbn)
    }

    fun updatePrice(isbn:String, price:String) =  viewModelScope.launch{
        repository.update(isbn,price)
    }

    fun update(book:Book) =  viewModelScope.launch{
        repository.update(book)
    }

    fun refresh() = viewModelScope.launch {

//        var _books : List<Book>
//         repository.getAll().collect {
//             _books = it
//        }
    }
}